#include <Game/GameFSM.h>

namespace pp
{
    Game::Game()
        : mpFSM(new GameFSM(this)),
          mpMainWindow(new MainWindow()),
          mpUITest(new UITest()),
          mpTimer(new ne::Timer()),
          mDeltaTime(0),
          mRequestExit(false),
          mExitStatus(0)
    {
    }

    bool Game::start()
    {
        mpFSM->reset();
        mpTimer->reset();
        return true;
    }

    bool Game::tick()
    {
        mDeltaTime = 0.001f * mpTimer->getIntervalMilliseconds();

        if (ne::Engine::GetSingleton().getKeyboard()->isKeyDown(ne::KK_ESC))
        {
            GameExitEvent exitEvent;
            mpFSM->onEvent(exitEvent);
        }
        
        GameTickEvent tickEvent;
        tickEvent.interval = mDeltaTime;
        mpFSM->onEvent(tickEvent);

        mpMainWindow->tick();
        mpUITest->tick();

        if (mRequestExit)
        {
            std::exit(mExitStatus);
        }

        return true;
    }

    bool Game::render()
    {
        mpMainWindow->render();
        mpUITest->render();
        return true;
    }

    void Game::requestExit(int status)
    {
        mRequestExit = true;
        mExitStatus = status;
    }

    uint32_t Game::getStateID() const
    {
        return mpFSM->getCurrentStateID();
    }

    Game::~Game()
    {
        delete mpMainWindow;
        delete mpUITest;
        delete mpFSM;
    }

    Game& Game::GetSingleton()
    {
        assert(mpInstance);
        return *mpInstance;
    }

    Game* Game::GetSingletonPtr()
    {
        return mpInstance;
    }
}
